const path = require('path');
const fs = require('fs');

function deleteall(path) {
  var files = [];
  if(fs.existsSync(path)) {
    files = fs.readdirSync(path);
    files.forEach(function(file, index) {
      var curPath = path + "/" + file;
      if(fs.statSync(curPath).isDirectory()) { // recurse
        deleteall(curPath);
      } else { // delete file
        fs.unlinkSync(curPath);
      }
    });
    fs.rmdirSync(path);
  }
};

/**
 * 删除根目录下的文件夹
 */
class DelDistPlugin {
  constructor(pathname) {
    this._pathname = pathname
  }
  apply(compiler){
    compiler.hooks.done.tap('DelDistPlugin', ({compilation}) => {
      // compilation.hooks.finishModules.tap('DelDistPlugin',()=>{
      //   console.log('--finishModules')
      // })
      setTimeout(()=>{
        deleteall(path.join(compilation.options.context,this._pathname));
      })
    });
  }
}

module.exports = DelDistPlugin;